<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Shop\Enum\AreaCodeEnum;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\AreaModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Model\ShopAttributeCategoryModel;
use App\Kuafu\Shop\Model\ShopAttributeMappingModel;
use App\Kuafu\Shop\Model\ShopAttributeModel;
use Illuminate\Console\Command;

class UpdateShopAttributeMapping extends Command
{
    protected $signature = 'shop:updateShopAttributeMapping';

    protected $description = '根据新的城市菜单分级修改门店属性值';

    public function handle()
    {

        // 门店属性值列表
        $shopAttributeList = ShopAttributeModel::query()->get();

        // 产品定价 单选 A级(一线+西藏) B级(新一/二/三线城市) C级(四/五线) S级(精选产品特殊定价) 其他
        $cityMenuLevelAttributeData = $shopAttributeList
            ->where('categoryId', ShopAttributeCategoryModel::CATEGORY_ID_11)
            ->map(function ($item) {
                $name = $item->name;
                if ($name != '西藏价') {
                    if ($name == '其他') {
                        $name = '';
                    } else {
                        $name = substr($name, 0, 1);// A级(一线) -- A
                    }
                }
                return [
                    'id'   => $item->id,
                    'name' => $name,
                ];
            })
            ->keyBy('name')
            ->toArray();

        // 城市对应
        $areaData = AreaModel::query()
                             ->where('level', AreaCodeEnum::AREA_CITY)
                             ->get()
                             ->keyBy('areaId')
                             ->toArray();

        Shop::query()
            ->join('shop_attribute_mapping', 'shop_attribute_mapping.shopId', '=', 'shops.id')
            ->whereIn('shops.status', [CodeEnum::SHOP_STATUS_NORMAL, CodeEnum::SHOP_STATUS_PREPARE])// 启用+筹备中
            ->whereIn('shop_attribute_mapping.attributeId', array_column($cityMenuLevelAttributeData, 'id'))
            ->where('shop_attribute_mapping.isDeleted', 0)
            ->select(['shop_attribute_mapping.*', 'shops.name', 'shops.shopCode', 'shops.city'])
            ->get()
            ->map(function ($shops) use ($cityMenuLevelAttributeData, $areaData) {
                $city = $shops['city'] ?? 0;// 城市code
                if ($city) {

                    // 产品定价 菜单等级
                    $menuLevel = $areaData[$city]['menuLevel'] ?? '';
                    $newId     = $cityMenuLevelAttributeData[$menuLevel]['id'] ?? 0;
                    if ($newId && $newId != $shops['attributeId']) {

                        dump($shops['shopCode'], $shops['name'], $menuLevel);

                        ShopAttributeMappingModel::query()
                                                 ->where('id', $shops['id'])
                                                 ->update(['attributeId' => $newId]);
                    }
                }

            });

    }
}
